package com.fwj.vo;

import com.fwj.config.Constants;
import com.fwj.exception.EsbSynException;
import com.fwj.pojo.ServiceInfo;
import com.jcraft.jsch.*;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.Properties;

public class SftpVo {
    public Channel channel;
    private ChannelSftp sftp = null;

    public Session sshSession;
    public ServiceInfo service_info;
    public String local_path;
    private Logger logger = Logger.getLogger(SftpVo.class);

    public Channel getChannel(ServiceInfo serviceInfo) {

        JSch jsch = new JSch();
        String host = serviceInfo.getIp();
        setLocalPath(host);

        int port = serviceInfo.getPort();
        String username = serviceInfo.getUsername();
        String password = serviceInfo.getPassword();
        String privateKeyPath = Constants.private_key_path;
        try {
            if ("".equals(host) || host == null) {
                logger.error("F5服务器配置格式错误...");
                throw new EsbSynException("F5服务器配置格式错误..");

            }
            if (!"".equals(privateKeyPath) && privateKeyPath != null) {
                jsch.addIdentity(privateKeyPath);
            }
            sshSession = jsch.getSession(username, host, port);
            //如果密码不为空，则添加
            if (!"".equals(password) && password != null) {
                sshSession.setPassword(password);
            }
            Properties sessionConfig = new Properties();
            //SSH 公钥检查机制 no、ask、yes
            sessionConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sessionConfig);
            sshSession.connect();
            channel = sshSession.openChannel("sftp"); // 打开SFTP通道
            channel.connect();
            //进行操作 如进入指定文件夹
            // channelSftp.cd(config.getFileDir());
        } catch (JSchException e) {
            logger.error("sftp getConnect error : " + e);
        }
        setService_info(serviceInfo);
        return channel;
    }

    private void setLocalPath(String host) {
         String f5_data=Constants.f5_datafile;
      // 如果能找到 [ip],则替换。
        if (f5_data.contains("[ip]"))
            f5_data=f5_data.replace("[ip]",host);

        local_path=f5_data;
    }

    public ServiceInfo getService_info() {
        return service_info;
    }

    public void setService_info(ServiceInfo service_info) {
        this.service_info = service_info;
    }

    @Override
    public String toString() {
        return "SftpVo{" +
                "channel=" + channel +
                ", sshSession=" + sshSession +
                ", serviceInfo=" + service_info +
                '}';
    }

    public void putFileToSftpServer(String filePath, String uploadPath) {
        try {
            sftp = (ChannelSftp) channel;
            File file = new File(filePath);

            if (!file.exists()) {
                throw new EsbSynException("本地路径有误" + filePath);
            }
            sftp.put(filePath, uploadPath);
            logger.info("上传到"+service_info.getIp()+"服务器成功!上传位置:" + uploadPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void closeResource() {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (sshSession != null) {
            if (sshSession.isConnected()) {
                sshSession.disconnect();
            }
        }
        logger.info("已关闭ssh连接!");
    }

}
